package com.tingyun.sign.pics.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.tingyun.sign.activity.service.ActivityService;
import com.tingyun.sign.core.entity.ScActivityBean;
import com.tingyun.sign.core.entity.ScPicsBean;
import com.tingyun.sign.core.entity.ScUManagerBean;
import com.tingyun.sign.pics.bean.ScPicsDto;
import com.tingyun.sign.pics.service.PicsService;
import com.tingyun.sign.utils.BaseController;
import com.tingyun.sign.utils.DateUtils;
import com.tingyun.sign.utils.Page;

@Controller
@RequestMapping("pics")
public class PicsController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(PicsController.class);
	
	@Autowired
	private PicsService picsService;
	@Autowired
	private ActivityService activityService;
	
	/**
	 * 上传照片
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> upload(@RequestParam(value = "file", required = false) MultipartFile[] files, HttpSession session, ScPicsBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			//校验文件
			if(files == null) {
				map.put("info", "上传的图片为空");
			}else {
				ScUManagerBean manager = getSessionUser(session);
				bean.setActivityId(bean.getActivityId());
				bean.setCtime(new Date());
				bean.setMtime(new Date());
				bean.setCuser(manager.getId());
				bean.setMuser(manager.getId());
				bean.setStatus(0);
				//插入数据库、写文件
				Integer result = picsService.addFile(files, bean);
				map.put("result", result);
			}
		} catch (Exception e) {
			log.error("图片上传失败", e.getMessage());
			map.put("info", e.getMessage());
		}
		return map;
	}

	/**
	 * 活动列表
	 */
	@RequestMapping(value = "list")
	public ModelAndView list(HttpSession session) {
		ModelAndView mv = new ModelAndView();
		List<ScActivityBean> acs = activityService.findAllActivities(getSessionUser(session).getType());
		mv.setViewName("pics/list");
		mv.addObject("acs",acs);
		return mv;
	}
	/**
	 * 照片列表
	 */
	@RequestMapping(value = "findPage", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> findPage(ScPicsBean bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		Page<ScPicsBean> page = picsService.findPicsPage(bean);
		map.put("rows", page.getResultList());
		map.put("total", page.getTotalCount());
		return map;
	}
	
}
